from django.db.models import Q
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django import forms
from django.shortcuts import get_object_or_404
from django.db import connection

from browsertests.results.models import Result
from browsertests.common.views import common_search
from browsertests.results.forms import ResultSearchForm, CompareUAForm
from browsertests.useragents.models import Useragent

def result_search(request):
    def filter_objects(form, result_list):
        if form.cleaned_data['type']:
            result_list = result_list.filter(test__type__in=form.cleaned_data['type'])

        file = form.cleaned_data['file']
        if file:
            result_list = result_list.filter(Q(test__file__contains=file) |
                                             Q(test__file2__contains=file))
        #if form.cleaned_data['flag']:
        #    result_list = result_list.filter(test__flags__in=form.cleaned_data['flag'])
        #if form.cleaned_data['tag']:
        #    result_list = result_list.filter(test__tags__in=form.cleaned_data['tag'])

        if form.cleaned_data['useragent']:
            result_list = result_list.filter(ua__in=form.cleaned_data['useragent'])
        if form.cleaned_data['succeeded'] != '---':
            result_list = result_list.filter(succeeded=form.cleaned_data['succeeded'] == 'True')
        if form.cleaned_data['status']:
            result_list = result_list.filter(status__in=form.cleaned_data['status'])

        return result_list.select_related()

    return common_search(request, 'results', reverse('result-search'), ResultSearchForm, Result,
                         'results/result_search.html', filter_objects)


def compare_ua(request):
    from_ua = None
    to_ua = None
    results = []
    unique_to_count = 0
    unique_from_count = 0

    if request.GET:
        form = CompareUAForm(request.GET)
        if form.is_valid():
            from_ua = get_object_or_404(Useragent.objects.select_related(),
                                        pk=form.cleaned_data["from_ua"])
            to_ua = get_object_or_404(Useragent.objects.select_related(),
                                      pk=form.cleaned_data["to_ua"])

            cursor = connection.cursor()
            cursor.execute("""SELECT t.id, t.full_id, r_from.id, r_from.succeeded,
                                  r_from.status, r_to.id, r_to.succeeded, r_to.status
                            FROM results_result r_from
                                 JOIN results_result r_to USING(test_id, test_version)
                                 JOIN tests_test t ON r_from.test_id = t.id
                            WHERE r_from.ua_id = %s AND
                                  r_to.ua_id = %s AND
                                  r_from.succeeded != r_to.succeeded""",
                           [from_ua.pk, to_ua.pk])
            for row in cursor.fetchall():
                test_id, test_full_id, from_id, from_succeeded, from_status, \
                to_id, to_succeeded, to_status = row
                results.append({
                    "kind": ("New Failures (regressions)" if from_succeeded
                             else "New Successes"),
                    "from_id": from_id,
                    "from_status": from_status,
                    "to_id": to_id,
                    "to_status": to_status,
                    "test_id": test_id,
                    "test_label": (test_full_id if test_full_id else test_id),
                })

            def count_unique_results(ua_0, ua_1):
                cursor.execute("""SELECT count(1)
                               FROM results_result r_from
                               WHERE r_from.ua_id = %s AND
                                 NOT EXISTS (SELECT 1 FROM results_result r_to WHERE
                                             r_to.ua_id = %s AND
                                             r_to.test_id = r_from.test_id AND
                                             r_to.test_version = r_from.test_version)""",
                               [ua_0.pk, ua_1.pk])
                return cursor.fetchone()[0]
            unique_to_count = count_unique_results(to_ua, from_ua)
            unique_from_count = count_unique_results(from_ua, to_ua)
    else:
        form = CompareUAForm()

    return render_to_response('results/compare_ua.html', {
        "form": form,
        "from_ua": from_ua,
        "to_ua": to_ua,
        "results": results,
        "unique_to_count": unique_to_count,
        "unique_from_count": unique_from_count,
    }, context_instance=RequestContext(request))
